<template>
	<view class="content">
		<!-- 撑开高度 -->
		<view class="" style="width: 100%;height: 160rpx;background-color: #2e60ff;border-radius: 0 0 60rpx 60rpx;">

		</view>
		<!-- end -->
		<!-- 内容部分 -->
		<view class="content1">
			<!-- 题目部分 -->
			<view class="inTitle">
				<view style="font-weight: bold;width: 100%;" v-html="content"></view>
				<view class="warning">
					<view class="">
						<u-icon name="error-circle-fill" style="font-size: 40upx;margin-right: 8rpx;margin-top: 8rpx;">
						</u-icon>
					</view>
					<view class=""><text>请注意上传答案图片数量最大为三张</text></view>
				</view>
			</view>
			<!-- end -->
			<!-- 选择图片部分 -->
			<view class="select">
				<u-upload :multiple="false" @on-success="success" @on-choose-complete="onChooseComplete" ref="uUpload"
					max-count='3' :action="action" :file-list="fileList" :auto-upload="false"></u-upload>
			</view>
			<!-- end -->

		</view>
		<!-- end -->

		<!-- 提交按钮 -->
		<view class="submit" @click="tuchSubmit">
			立即提交
		</view>
		<!-- end -->

	</view>
</template>

<script>
	import crypto from '../../utlis/crypto.js'
	export default {
		data() {
			return {
				content: '', // 题目
				// 演示地址，请勿直接使用
				action: 'https://vvv.52ecode.cn/api/Upload/uploadFileslmg',
				fileList: [],
				imageType: ['image/png', 'image/jpeg', 'image/jpg'], //图片验证类型
				imageList: [],
				dataIn: [],
				imgNum: 0,
				dataInfo: {}, //基础信息
				// 这里直接获取内部的lists变量即可
				lists: []
			}
		},
		onLoad() {

		},
		created() {

		},
		methods: {
			getTitle() {
				this.$u.post('https://vvv.52ecode.cn/api/v1.QuestionImgCreate/getQuestion', {
					question_id: this.dataInfo.qid,
				}).then(res => {
					const {
						title
					} = res.data
					this.content = title;
				})
			},
			success(e) {},
			photoCompress: function(file, objDiv, type) {
				var ready = new FileReader();
				ready.readAsDataURL(file);
				const _this = this;
				ready.onload = function() {
					var fileResult = this.result;
					_this.canvasDataURL(fileResult, objDiv, type)
				}
			},
			canvasDataURL: function(path, callback, type) {
				var img = new Image();
				img.src = path;
				var objCompressed = {}
				img.onload = function() {
					var that = this;
					//默认压缩后图片规格（0.1-1）越小压缩越强，质量越差
					var quality = 0.5;
					var w = that.width;
					var h = that.height;
					var scale = w / h;
					//实际要求
					w = objCompressed.width || w;
					h = objCompressed.height || (w / scale);
					//生成canvas
					var canvas = document.createElement('canvas');
					var ctx = canvas.getContext('2d');
					// 创建属性节点
					var anw = document.createAttribute("width");
					anw.nodeValue = w;
					var anh = document.createAttribute("height");
					anh.nodeValue = h;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					ctx.drawImage(that, 0, 0, w, h);

					var base64 = canvas.toDataURL(type, quality);
					// 回调函数返回base64的值
					callback(base64);
				}
			},

			onChooseComplete: function(res) {
				let len = res.length - 1;
				var size = res[len].file.size; //69457
				var type = res[len].file.type; //image/png
				var name = res[len].file.name;
				if (!this.imageType.includes(type)) { //没在
					uni.showToast({
						title: '图片类型不合法',
						duration: 2000,
						icon: 'none'
					})
					return;
				}

				if ((size / 1024) > (1024 * 12)) {
					uni.showToast({
						title: '图片文件不能大于5M!',
						duration: 2000,
						icon: 'none'
					})
					return;
				}

				uni.showLoading({
					title: "压缩图片中..."
				})
				//调用图片压缩接口
				this.photoCompress(res[len].file, (base64Codes) => {
					this.uploadImage(base64Codes);
				}, type)
			},

			uploadImage: function(base) {
				this.$u.post('https://vvv.52ecode.cn/api/Upload/uploadFilesImg', {
					base: base
				}).then(res => {
					uni.hideLoading();
					this.dataIn.push(res.data)
					this.imageList = this.dataIn.join()
				}).catch(err => {
					uni.hideLoading();
				});

			},
			tuchSubmit() {
				if (this.imageList) {
					this.$u.post('https://vvv.52ecode.cn/api/v1.QuestionImgCreate/index', {
						exam_id: this.dataInfo.eid,
						question_id: this.dataInfo.qid,
						img_url: this.imageList,
						user_id: this.dataInfo.uid
					}).then(res => {
						if (res.code == 200) {
							this.$refs.uUpload.clear();
							uni.showToast({
								title: res.data,
								icon: 'none'
							})
							this.fileList = []
						}
						if (res.code == 400) {
							uni.showToast({
								title: res.msg,
								icon: 'error'
							})
							this.fileList = []
						}
					})
				} else if (!this.imageList) {
					uni.showToast({
						title: '请选择图片',
						icon: 'error'
					})
				}
			},
			urlToObj(str) {
				var obj = {};
				var arr1 = str.split("?");
				var arr2 = arr1[1].split("&");
				for (var i = 0; i < arr2.length; i++) {
					var res = arr2[i].split("=");
					obj[res[0]] = res[1];
				}
				return obj;
			}
		},
		onLoad(options) {
			let key = encodeURIComponent(options.key)
			let val = key.replace(/%20/g, "+")
				.replace(/%2F/g, '/')
				.replace(/%3D/g, '=')
				.replace(/%3F/g, '?')
				.replace(/%2E/g, '.')
				.replace(/%3A/g, ':')
				.replace(/%23/g, '#')
				.replace(/%25/g, '%')
				.replace(/%26/g, '&')
				.replace(/%2B/g, '+')
				.replace(/%5C/g, '\\')
			try {
				this.dataInfo = this.urlToObj(crypto.decrypt(val))
				this.getTitle();
			} catch (e) {
			}
		},
		onReady() {

		}
	}
</script>

<style scoped>
	.warning {
		background-color: #faa52c;
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		width: 100%;
		text-align: center;
		color: red;
		font-size: 30upx;
		margin-top: 40rpx;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.submit {
		margin-bottom: 120rpx;
		background-color: #4379ff;
		width: 220rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 30rpx;
		letter-spacing: 1.2pt;
		font-size: 30upx;
		margin-left: 50%;
		margin-top: 200rpx;
		transform: translateX(-50%);
		color: #FFFFFF;
		height: 60rpx;
	}

	.submit:active {
		background-color: #59d3ff;
	}

	.select {
		margin-top: 40rpx;
		width: auto;
	}

	.inTitle {
		font-weight: 520;
		letter-spacing: 1pt;
	}

	.content1 {
		width: auto;
		line-height: 1.5;
		padding: 24rpx 16rpx;
		margin-left: 28rpx;
		margin-right: 28rpx;
		margin-top: -160rpx;
		min-height: 50vh;
		border-radius: 8rpx;
		background-color: #FFFFFF;
		box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}
</style>
